package com.wanchuang.hepos.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.google.protobuf.InvalidProtocolBufferException;
import com.wanchuang.architecture.utils.APKVersionCodeUtils;
import com.wanchuang.hepos.R;
import com.wanchuang.hepos.bridge.data.repository.Apis;
import com.wanchuang.hepos.help.DialogUtils;
import com.wanchuang.hepos.help.PermissionHelper;
import com.wanchuang.hepos.net.NetworkManager;
import com.wanchuang.hepos.net.interfaces.OnRequestCallBack;
import com.wanchuang.hepos.proto.Index;
import com.wanchuang.hepos.proto.MemberOuterClass;
import com.wanchuang.hepos.proto.Merchant;
import com.wanchuang.hepos.ui.base.BaseActivity;
import com.wanchuang.hepos.ui.updateutil.UpdateManager;
import com.wanchuang.hepos.ui.utils.GPS_Interface;
import com.wanchuang.hepos.ui.utils.GPS_Presenter;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class MainActivity extends BaseActivity implements GPS_Interface {

    private long mExitTime;
    private NavController nav;
    private int INSTALL_PERMISS_CODE = 10000;
    private Location mLocation;

    private GPS_Presenter gps_presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        nav = Navigation.findNavController(this, R.id.main_fragment_host);
        checkVersion();
        gps_presenter = new GPS_Presenter(this, this);
//        getLastKnownLocation();
    }


    @Override
    public void onBackPressed() {
        if (nav.getCurrentDestination() != null) {
            if (nav.getCurrentDestination().getId() == R.id.mainRootFragment && (System.currentTimeMillis() - mExitTime) > 2000) {
                showShortToast("再按一次退出程序");
                mExitTime = System.currentTimeMillis();
            } else {
                mSharedViewModel.isHomeLoad.setValue(true);
                super.onBackPressed();
            }
        }
    }


    private void checkVersion() {
        Index.get_app_version_info.Builder builder = Index.get_app_version_info.newBuilder();
        builder.setClient("android");
        NetworkManager.INSTANCE.post(Apis.versionCode, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) {
                checkVerison(response);
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                hideProgress();
            }
        });

    }

    private void checkVerison(byte[] response) {
        String versionName = APKVersionCodeUtils.getVerName(this);
        Index.get_app_version_info versionBean = null;
        try {
            versionBean = Index.get_app_version_info.parseFrom(response);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        Log.e("mango", "checkVerison: " + versionBean);
        // 改为匹配版本号
        float serviceVersion = Float.parseFloat(versionBean.getVersion());
        float locationeVersion = Float.parseFloat(versionName);
        if (locationeVersion < serviceVersion) {
            UpdateManager.getInstance()
                    .setContext(this)
                    .setFragmentManager(getSupportFragmentManager())
                    .setUrl(versionBean.getDownloadUrl())
                    .setIsforce(versionBean.getForce())
                    .setContent(versionBean.getContext())
                    .start();
        }
    }


    /**
     * 开启安装未知来源权限
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallPermissionSettingActivity() {
        Uri packageURI = Uri.parse("package:" + getPackageName());
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivityForResult(intent, INSTALL_PERMISS_CODE);
    }


    private void getLastKnownLocation() {
        List<String> permissions = new ArrayList<>();
        permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
        permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        permissions.add(Manifest.permission.CAMERA);
        PermissionHelper.getInstance().getPermissionGroup(this, new PermissionHelper.PermissionCallBack() {
            @Override
            public void onSuccess() {
                // 获取手机品牌
                LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
                boolean gpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                if (gpsEnabled) {
//                    showProgress();
                    if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                            ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        return;
                    }
                    mLocationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,      //GPS定位提供者
                            500,       //更新数据时间为1秒
                            1,      //位置间隔为1米
                            //位置监听器
                            new LocationListener() {  //GPS定位信息发生改变时触发，用于更新位置信息

                                @Override
                                public void onLocationChanged(Location location) {
                                    //GPS信息发生改变时，更新位置
//                                    locationUpdates(location);
                                }

                                @Override
                                //位置状态发生改变时触发
                                public void onStatusChanged(String provider, int status, Bundle extras) {
                                }

                                @Override
                                //定位提供者启动时触发
                                public void onProviderEnabled(String provider) {
                                }

                                @Override
                                //定位提供者关闭时触发
                                public void onProviderDisabled(String provider) {
                                }
                            });
                    //从GPS获取最新的定位信息
                    Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    locationUpdates(location);    //将最新的定位信息传递给创建的locationUpdates()方法中
                } else {
//                    DialogUtils.showHitDialog(MainActivity.this, "提示", "定位失败,请打开GPS服务后重试");
                }
            }

            @Override
            public void onFail() {
                Toast.makeText(MainActivity.this, "获取权限失败", Toast.LENGTH_SHORT).show();
            }
        }, permissions);


    }

    public void locationUpdates(Location location) {  //获取指定的查询信息
        //如果location不为空时
        if (location != null) {
            hideProgress();
            StringBuilder stringBuilder = new StringBuilder();        //使用StringBuilder保存数据
            //获取经度、纬度、等属性值
            stringBuilder.append("您的位置信息：\n");
            stringBuilder.append("经度：");
            stringBuilder.append(location.getLongitude());
            stringBuilder.append("\n纬度：");
            stringBuilder.append(location.getLatitude());
            mLocation = location;
            List<Address> address = getAddress(location);
            Log.e("地址", address.toString());
            Merchant.giving_address.Builder builder = Merchant.giving_address.newBuilder();
            builder.setProvinceName(address.get(0).getAdminArea()).setCityName(address.get(0).getLocality());
            NetworkManager.INSTANCE.post(Apis.giving_address, builder.build().toByteArray(), new OnRequestCallBack() {
                @Override
                public void onOk(byte[] bytes) {
                }
                @Override
                public void onError(int code, String errorMessage) {
                    if (code == 200)
                    {
                        Log.e("地址上传","成功");
                    }
                }
            });


        }
    }


    private List<Address> getAddress(Location location) {
        List<Address> result = null;
        try {
            if (location != null) {
                Geocoder gc = new Geocoder(this, Locale.getDefault());
                result = gc.getFromLocation(location.getLatitude(),
                        location.getLongitude(), 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    @Override
    public void gpsSwitchState(boolean gpsOpen) {
        if (gpsOpen) {
            getLastKnownLocation();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        //释放资源
        if (gps_presenter != null) {
            gps_presenter.onDestroy();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        getLastKnownLocation();
    }
}
